const mfs = require('./mfs');
const utils = require('./utils');
const ccc = require('./ccc');
// step 2 读取配置
const configPath = mfs.join(__dirname, 'config_wx_mini.json');
const config = require(configPath);


//初始化配置文件
initConfig(process.argv[2]);


const projectPath = mfs.join(__dirname, '..');
// 调用打包
if (utils.isMac()) {
    config.enginePath = '/Applications/Cocos/Creator/' + config.engineVer + '/CocosCreator.app/Contents';
} else {
    config.enginePath = 'C:/CocosDashboard/resources/.editors/Creator/' + config.engineVer;
}



/**根据命令参数设置一下配置 */
function initConfig(arg) {
    const isDebug = arg.indexOf("debug") != -1;
    config.debug = `${isDebug}`
    console.log("=====config.debug====", config.debug)
    console.log("=====config.buildPath====", config.buildPath)
    console.log("=====config.platform====", config.platform)
    console.log("=====config.nativePath====", config.nativePath)
}


/**
 * 压图
 * 报错的话需要安装 brew install little-cms2
 * 或者把auto-pack下的 little-cms2 复制到下面的目录
 * /usr/local/opt
 */
function compressImg(config) {
    console.log("=======开始压缩资源=========");
    const compress_cmd = `python3 compressimg.py ${config.nativePath}/assets`
    utils.runShSync(compress_cmd);
    const sub_compress_cmd = `python3 compressimg.py ${config.nativePath}/subpackages`
    utils.runShSync(sub_compress_cmd);
    console.log("=====压缩资源完成===========");
}

/**加密 */
function encryptionImg(config) {
    console.log("=======开始加密资源=========");
    const res_path = mfs.join(__dirname, `${config.nativePath}/assets/`);
    console.log("res_path = ", res_path);
    utils.runShSync(`python3 en.py ${res_path}`);
    const sub_res_path = mfs.join(__dirname, `${config.nativePath}/subpackages/`);
    console.log("sub_res_path = ", sub_res_path);
    utils.runShSync(`python3 en.py ${sub_res_path}`);
    console.log("=======加密资源完成=========");
}

/**开始构建 */
function pack() {
    console.log("==projectPath:", projectPath)
    config.path = projectPath;
    console.log("===替换版本号配置====");
    //构建cocos
    ccc.pack(config);

    //压缩
    compressImg(config);
    //加密
    // encryptionImg(config);

    process.exit(0);
}


console.log("\n打包模式      = ", config.debug ? "debug" : "release")
console.log("游戏名称(CH)  = ", config.appName)
console.log("游戏名称(EN)  = ", config.title)

console.log('\n输入Y(y)以确认打包 输入N(n)退出打包');

let stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', function (key) {
    if (key === '\u0003') {
        console.log("===key===", key);
        process.exit();
    }
    // ctrl-c ( end of text )
    if (key === 'n' || key === 'N') {
        console.log("退出打包");
        process.exit();
    }

    if (key === 'Y' || key === 'y') {
        pack();
    }
    // write the key to stdout all normal like
    process.stdout.write(key);
});


